//
//  WKMainController.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/6.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit

class WKMainController: UITabBarController {

    //监听按钮点击事件
    @objc private func clickButton(){
    
        print("点击了我")
        
        //判断用户是否登录
        var vc: UIViewController
        if UserAccountViewModel.sharedUserAccount.userLogin {
        
            vc = WKComposeViewController()
        }else {
        
            vc = OAuthViewController()
        }
    
        //添加导航控制器
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //添加控制器
        addChicldContrrollers()
        
        //添加自定义按钮
        setupComposedButton()
    }

    //将自定义按钮搁置到最上层
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composeButton)
        
    }
    
    
    //创建自定义按钮
   private lazy var composeButton: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    
    
    
    
}


//创建自控制器
extension WKMainController{
    
    
    

    private func setupComposedButton(){
    
        
        //设置按钮的位置
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count) - 1
        
        composeButton.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
            //添加按钮
        tabBar.addSubview(composeButton)
    
        composeButton .addTarget(self, action: "clickButton", forControlEvents: .TouchUpInside)
    
    }
    

    private func addChicldContrrollers(){
    
        //添加控制器
        addChicldContrroller(WKHomeViewController(), title: "首页", image: "tabbar_home")
        addChicldContrroller(WKMessageViewController(), title: "消息", image: "tabbar_message_center")

        //添加一个viewController
        addChildViewController(UIViewController())
        
        addChicldContrroller(WKDiscoverViewController(), title: "发现", image: "tabbar_discover")
        addChicldContrroller(WKProfileViewController(), title: "我", image: "tabbar_profile")
    
    
    }
    
    
    
    //添加控制器
    private func addChicldContrroller(vc: UIViewController , title: String , image: String){
    
        //设置标题
        vc.title = title
        
        //设置图片
        vc.tabBarItem.image = UIImage(named: image)
        
        //添加导航控制器
        let nav = UINavigationController(rootViewController: vc)
        
        //添加导航控制器
        addChildViewController(nav)
    
    }

}




